package com.lovo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.dao.IMovieDao;
import com.lovo.dao.IOrderDao;
import com.lovo.entity.MovieEntity;
import com.lovo.entity.OrderEntity;
import com.lovo.util.PinYinUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RequestMapping
@RestController
public class MTController {
    @Autowired
    IMovieDao movieDao;

    @Autowired
    IOrderDao orderDao;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 设置回调方法
     */
    RabbitTemplate.ConfirmCallback callback = (CorrelationData correlationData, boolean b, String s) -> {
        System.out.println("进入回调方法");
        //投递成功
        if (b) {
            //获得关联数据,movieId
            String orderIdStr = correlationData.getId();
            int orderId = Integer.parseInt(orderIdStr);
            System.out.println("orderId=" + orderId);
            //把订单状态改为1表示下单成功待处理
            OrderEntity orderEntity = orderDao.selectById(orderId);
            System.out.println(orderEntity);
            orderEntity.setTag(1);
            System.out.println("生产者投递成功");
            orderDao.updateById(orderEntity);
        } else {
            System.out.println("投递失败");
        }
    };

    @GetMapping("showMyOrder")
    public List<OrderEntity> showMyOrder() {
        return orderDao.selectList(null);
    }

    @GetMapping("allTicket")
    public List<MovieEntity> allTicket() {
//        return (List<MovieEntity>) movieDao.findAll();
        return movieDao.selectList(null);
    }

    @PutMapping("buy/{movieId}/{price}/{buyNum}")
    public boolean buy(@PathVariable int movieId, @PathVariable int price, @PathVariable int buyNum) {

        //开启手动确认
        rabbitTemplate.setMandatory(true);//开启消息确认
        //绑定回调函数
        rabbitTemplate.setConfirmCallback(callback);


        OrderEntity orderEntity = new OrderEntity();
        //获得电影实体
        MovieEntity movie = movieDao.selectById(movieId);
        //封装订单号：电影名的字母开头，年月日，ID
        String str1 = PinYinUtil.getPinYinHeaderChar(movie.getMovieName());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String str2 = dateTimeFormatter.format(LocalDate.now());
        //订单编号
        String orderNum = str1 + str2 + movieId + System.currentTimeMillis();
        orderEntity.setOrderNum(orderNum);
        orderEntity.setMovieEntity(movie);
        orderEntity.setBuyPrice(price);
        orderEntity.setBuyNum(buyNum);
        orderEntity.setMovieId(movieId);
        //订单放入到本地数据库
        int x = orderDao.insert(orderEntity);
        QueryWrapper<OrderEntity> wq = new QueryWrapper<>();
        wq.eq("orderNum", orderEntity.getOrderNum());
        OrderEntity ord = orderDao.selectOne(wq);
        //组装关联数据
        CorrelationData correlationData = new CorrelationData(String.valueOf(ord.getOderId()));
        if (x != 0) {
            //把订单发送到电影院，让电影院出票
            //rabbitTemplate.convertAndSend("orderEx", "buy.movie", order);
            QueryWrapper<OrderEntity> q = new QueryWrapper();
            q.eq("orderNum", orderNum);
            //连带传输关联数据至后台，将数据放入队列后进入回调函数进行确认
            rabbitTemplate.convertAndSend("orderEx", "buy.movie", orderDao.selectOne(q), correlationData);
            return true;
        }
        return false;
    }

    @PutMapping("changeTag/{orderNum}/{tag}")
    public boolean changeTag(@PathVariable("orderNum") String orderNum, @PathVariable("tag") int tag) {
        //获得订单对象
        //OrderEntity order = orderDao.findDistinctFirstByOrderNum(orderNum);
        QueryWrapper<OrderEntity> q = new QueryWrapper<>();
        q.eq("orderNum", orderNum);
        OrderEntity order = orderDao.selectOne(q);
        order.setTag(tag);
        //更新前台数据库
        int x = orderDao.updateById(order);
        //出票成功后更新票数
        if (tag == 2) {
            MovieEntity m = movieDao.selectById(order.getMovieId());
            m.setMovieNum(m.getMovieNum() - order.getBuyNum());
            movieDao.updateById(m);
        }
        if (x != 0) {
            return true;
        }
        return false;
    }
}
